import sys
from PyQt4 import QtGui, QtCore

def timeformat(second):
	s = second%60
	m = (second/60)%60
	h = int(second/(60*60))
	return "time %02d:%02d:%02d" % (h,m,s)

STOP = "stop"
PAUSE = "pause"
RUN = "run"

class SimpleTimer(QtGui.QMainWindow):
	def __init__(self):
		self._initgui()
		self.count = 0
		self.clock = QtCore.QTimer(self)
		self.clock.setInterval(1000)
		self.connect(self.clock, QtCore.SIGNAL("timeout()"), self.tick)
		self.state = STOP
	
	def closeEvent(self, event):
		self.stop()
		event.accept()

	def _initgui(self):
		QtGui.QMainWindow.__init__(self)

		self.resize(350, 100)
		self.setWindowTitle("Timer")

		body = QtGui.QWidget(self)

		self.box = QtGui.QVBoxLayout()
		self.box.setSpacing(5)
		body.setLayout(self.box)
		self.setCentralWidget(body)

		self._addgui()

	def _addgui(self):
		start = QtGui.QPushButton("start")
		self.connect(start, QtCore.SIGNAL("clicked()"), self.start)
		self.box.addWidget(start)

		pause = QtGui.QPushButton("pause")
		self.connect(pause, QtCore.SIGNAL("clicked()"), self.pause)
		self.box.addWidget(pause)

		stop = QtGui.QPushButton("stop")
		self.connect(stop, QtCore.SIGNAL("clicked()"), self.stop)
		self.box.addWidget(stop)
		
		self.timerlabel = QtGui.QLabel(timeformat(0))
		self.box.addWidget(self.timerlabel)

	def start(self):
		print("start")
		if self.state==STOP: 
			self.count = 0	
			self.timerlabel.setText(timeformat(0))
		self.state = RUN
		self.clock.start()
	
	def stop(self):
		self.clock.stop()
		self.state = STOP
	
	def pause(self):
		self.clock.stop()
		self.state = PAUSE
	
	def tick(self):
		self.count += 1
		self.timerlabel.setText(timeformat(self.count))

app = QtGui.QApplication(sys.argv)
main = SimpleTimer()
main.show()
sys.exit(app.exec_())
